package co.yixiang.modules.system.service.impl;

import cn.hutool.core.convert.Convert;
import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.common.utils.QueryHelpPlus;
import co.yixiang.modules.system.domain.Partner;
import co.yixiang.modules.system.domain.VxUser;
import co.yixiang.modules.system.dto.PartnerDto;
import co.yixiang.modules.system.dto.queryCriteria.PartnerQueryCriteria;
import co.yixiang.modules.system.mapper.PartnerMapper;
import co.yixiang.modules.system.service.PartnerService;
import co.yixiang.modules.system.service.VxUserService;
import co.yixiang.modules.system.util.ConfigConstant;

import co.yixiang.modules.system.util.WxMsgPush;
import co.yixiang.modules.system.util.vo.WxMsgVo;
import co.yixiang.utils.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zf
 * @date 2021-10-09
 */
@Service
@AllArgsConstructor
//@CacheConfig(cacheNames = "partner")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class PartnerServiceImpl extends BaseServiceImpl<PartnerMapper, Partner> implements PartnerService {

    @Autowired
    private final VxUserService vxUserService;

    @Autowired
    private final WxMsgPush wxMsgPush;

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(PartnerQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<Partner> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", Convert.toList(PartnerDto.class, page.getList()));
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<Partner> queryAll(PartnerQueryCriteria criteria) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(Partner.class, criteria));
    }


    @Override
    public void download(List<PartnerDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PartnerDto partner : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put(" openId", partner.getOpenId());
            map.put("推荐人名称", partner.getShareName());
            map.put("名称", partner.getName());
            map.put("手机号", partner.getPhone());
            map.put("详细地址", partner.getArea());
            map.put("申请状态", partner.getPartnerStatus());
            map.put("创建时间", partner.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public void check(Partner resources) {
        this.updateById(resources);

        if (!StringUtils.isEmpty(resources.getPhone())) {
            QueryWrapper<VxUser> wrapper = new QueryWrapper<>();
            wrapper.eq("open_id", resources.getOpenId());
            VxUser vxUser = vxUserService.getOne(wrapper);
            if (vxUser != null) {
                String url = ConfigConstant.HHR_URL + "?id=" + resources.getId();
                LocalDateTime time = LocalDateTime.now();

                DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                String now = dtf2.format(time);
                //消息推送
                WxMsgVo msgVo = WxMsgVo.builder()
                        .first("您好！下级合伙人审核状态已更新")
                        .keyword1(resources.getName() + "｜" + resources.getPhone())
                        .keyword2(now)
                        .openId(resources.getOpenId())
                        .url(url)
                        .remark("点击查看详情，查看审核进展！")
                        .build();
                wxMsgPush.SendWxMsg(msgVo);
                if (resources.getPartnerStatus() == 4) {
                    resources.setPartnerStatus(1);
                    vxUser.setId(0);
                }
                //更新申请合伙人信息
                VxUser build = VxUser.builder()
                        .superId(vxUser.getId())
                        .ident(resources.getPartnerStatus())
                        .build();
                UpdateWrapper<VxUser> update = new UpdateWrapper<>();
                update.eq("phone", resources.getPhone());
                vxUserService.update(build, update);
            }
        }
    }
}
